package com.surprise.base.util;

import java.io.IOException;

import lombok.Data;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;


/**
 * XMLUtils.java
 * @author nick
 * 2015年1月29日
 */
public class XMLUtils {
    private static ObjectMapper mapper;

    static {
        JacksonXmlModule module = new JacksonXmlModule();
        module.setDefaultUseWrapper(false);
        JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
        mapper = new XmlMapper(module);
        mapper.registerModule(jaxbAnnotationModule);
        mapper.setSerializationInclusion(Include.NON_NULL);

        // AnnotationIntrospector introspector = new
        // JacksonAnnotationIntrospector();
        // mapper.setAnnotationIntrospector(introspector);
    }

    public static <T> T fromXML(String xml, Class<T> c)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(xml, c);
    }

    public static <T> T fromXml(String xml, Class<T> c, Class... t)
            throws JsonParseException, JsonMappingException, IOException {
        JavaType javaType = mapper.getTypeFactory().constructParametricType(c,
                t);
        return mapper.readValue(xml, javaType);
    }

    public static String toXml(Object o) throws JsonProcessingException {
        String xml = mapper.writeValueAsString(o);
        return xml;
    }
}

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JacksonXmlRootElement(localName = "xml")
class A {
    private int a = 1;
    private int b = 2;
    private String c = "3";
}